<template>
  <Layout>
    <div class="login-container">
      <div class="login-box">
        <!-- 登录类型选择菜单 -->
        <div class="login-tabs">
          <div 
            class="tab-item" 
            :class="{ active: loginType === 'volunteers' }"
            @click="switchLoginType('volunteers')"
          >
            志愿者登录
          </div>
          <div 
            class="tab-item" 
            :class="{ active: loginType === 'organizations' }"
            @click="switchLoginType('organizations')"
          >
            志愿队伍登录
          </div>
          <div 
            class="tab-item" 
            :class="{ active: loginType === 'admin' }"
            @click="switchLoginType('admin')"
          >
            管理部门登录
          </div>
        </div>
        
        <!-- 登录表单 -->
        <div class="login-form">
          <h3 class="login-title">
            {{ 
              loginType === 'volunteers' ? '志愿者登录' : 
              loginType === 'organizations' ? '志愿队伍登录' : 
              '管理部门登录' 
            }}
          </h3>
          <el-form>
            <el-form-item>
              <el-input 
                v-model="loginForm.username" 
                :placeholder="getPlaceholder('username')"
                prefix-icon="User"
              />
            </el-form-item>
            
            <el-form-item>
              <el-input 
                v-model="loginForm.password" 
                type="password" 
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-button type="primary" @click="handleLogin" class="login-btn">
              登录
            </el-button>
          </el-form>

          <div class="form-footer">
            <div class="links">
              <router-link 
                to="/register" 
                @click.prevent="handleRegisterClick(loginType)"
              >还没有账号？立即注册</router-link>
            </div>
            <div class="links">
              <router-link 
                to="/lossPassword" 
              >忘记密码</router-link>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios';
import Layout from '@/components/Layout.vue'

const router = useRouter()
const route = useRoute()
const loginType = ref('volunteers')
const loginForm = ref({
  username: '',
  password: ''
})

// 刷新验证码
const refreshVerifyCode = () => {
  // 这里可以调用后端生成验证码的接口
}

// 监听 localStorage 中的 loginTable 变化
watch(() => localStorage.getItem('loginTable'), (newType) => {
  if (newType) {
    loginType.value = newType
  }
}, { immediate: true })

// 根据登录类型获取不同的placeholder
const getPlaceholder = (field) => {
  if (field === 'username') {
    switch (loginType.value) {
      case 'volunteers':
        return '请输入用户名或身份证号码'
      case 'organizations':
        return '请输入团队账号'
      case 'admin':
        return '请输入管理员账号'
      default:
        return '请输入用户名'
    }
  }
  return ''
}

// 切换登录类型
const switchLoginType = (type) => {
  loginType.value = type
  localStorage.setItem('loginTable', type)
  loginForm.value = {
    username: '',
    password: ''
  }
  refreshVerifyCode()
}

onMounted(() => {
  // 获取存储的登录类型
  const type = localStorage.getItem('loginTable')
  if (type) {
    loginType.value = type
  }
  // 在组件挂载后初始化验证码
  refreshVerifyCode()
})

// 检查注册表单是否有内容
const checkFormContent = () => {
  const form = JSON.parse(localStorage.getItem('registerFormData') || '{}')
  return Object.values(form).some(value => value !== '')
}

// 处理注册点击
const handleRegisterClick = async (type) => {
  if (route.path === '/register' && checkFormContent()) {
    try {
      await ElMessageBox.confirm(
        '当前页面信息未保存，切换将丢失已填写的信息，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      localStorage.removeItem('registerFormData')
      localStorage.setItem('loginTable', type)
      router.push('/register')
    } catch {
      return
    }
  } else {
    localStorage.setItem('loginTable', type)
    router.push('/register')
  }
}

const handleLogin = () => {
  console.log('Sending login request...');
  if (!loginForm.value.username) {
    ElMessage.error('请输入用户名');
    return;
  }
  if (!loginForm.value.password) {
    ElMessage.error('请输入密码');
    return;
  }
  console.log('开始调用后端接口，loginType.value =', loginType.value);
  let loginUrl = 'http://localhost:9090/volunteers/login';
  let loginData = {
    name: loginForm.value.username,
    password: loginForm.value.password
  };

  if (loginType.value === 'organizations') {
    
    loginUrl = 'http://localhost:9090/api/organization/login';
    loginData = {
      organizationName: loginForm.value.username,
      password: loginForm.value.password
    };
  } else if (loginType.value === 'admin') {
    
    loginUrl = 'http://localhost:9090/volunteers/login';
    loginData = {
      name: loginForm.value.username,
      password: loginForm.value.password
    };
  }

  axios.post(loginUrl, loginData)
  .then(response => {
    console.log("测试提交")
    if (response.data.success) {
      const userData = response.data.data;
      //统一存储用户信息
      localStorage.setItem('username', loginForm.value.username);
      //根据登录类型和用户身份跳转到不同的页面
      console.log(loginType.value === 'volunteers');
      if (loginType.value === 'volunteers') {
        localStorage.setItem('volunteerId', userData.volunteerId);
        if (userData.isAdmin === 1) {
          localStorage.setItem('type', "user");
          router.push('/home');
        } else {
          ElMessage.error('账号不存在，请重新登录。');
        }
      }else if (loginType.value === 'organizations') {
        localStorage.setItem('type', "organizations");
        localStorage.setItem('organid', userData.organizationId);
        router.push('/home');
      }else if (loginType.value === 'admin') {
        //检查后端返回的isAdmin字段
        if (userData.isAdmin === 0) {
          localStorage.setItem('type', "admin");
          const currentPort = window.location.port; // 获取当前端口号
          if (currentPort === '5173') {
            // 跳转时使用 replace 而非 push
            window.location.replace('http://localhost:5174/#/tabs');
          } else if (currentPort === '5174') {
            window.location.replace('http://localhost:5173/#/tabs');
          }
        } else {
          ElMessage.error('该账户不是管理员，请重新登录。');
        }
      }
    } else {
        ElMessage.error(response.data.message); // 直接使用后端返回的message
    }
  })
  .catch(error => {
    // 捕获网络错误或状态码非2xx的情况
    if (error.response && error.response.data) {
        // 处理结构化错误（如500错误）
        const msg = error.response.data.message || '请求失败';
        ElMessage.error(msg);
    } else {
        ElMessage.error('网络异常，请检查连接');
    }
  });
};
</script>

<style scoped>
.login-container {
  width: 100%;
  flex: 1;
  background-image: url('@/assets/images/login-bg.jpg');
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
}

.login-box {
  width: 800px;
  margin: 40px auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  z-index: 1;
}

.login-tabs {
  width: 200px;
  background-color: #f8f9fa;
  border-right: 1px solid #eee;
}

.tab-item {
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
  color: #666;
  text-align: center;
  border-bottom: 1px solid #eee;
  position: relative;
}

.tab-item:hover {
  background-color: #f0f0f0;
  color: #e31436;
}

.tab-item.active {
  color: #e31436;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: #e31436;
}

.login-form {
  flex: 1;
  padding: 30px;
  transition: all 0.3s ease;
}

.login-btn {
  width: 100%;
  height: 40px;
  font-size: 16px;
  margin-bottom: 20px;
}

.form-footer {
  text-align: center;
  margin-top: 15px;
}

.links {
  display: flex;
  justify-content: center;
  gap: 15px;
  color: #666;
  margin-bottom: 10px;
}

.links a {
  color: #666;
  text-decoration: none;
  font-size: 14px;
  position: relative;
  transition: all 0.3s ease;
  padding: 5px 10px;
  border-radius: 4px;
}

.links a:hover {
  color: #e31436;
  background-color: rgba(227, 20, 54, 0.05);
}

.links a::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 2px;
  background-color: #e31436;
  transition: all 0.3s ease;
  transform: translateX(-50%);
}

.links a:hover::after {
  width: 80%;
}

@media (max-width: 768px) {
  .login-box {
    width: 100%;
    flex-direction: column;
  }

  .login-tabs {
    width: 100%;
    display: flex;
    border-right: none;
    border-bottom: 1px solid #eee;
  }

  .tab-item {
    flex: 1;
    padding: 15px;
    border-bottom: none;
  }

  .tab-item.active {
    border-right: none;
    border-bottom: 2px solid #e31436;
  }
}

.login-title {
  font-size: 24px;
  color: #333;
  text-align: center;
  margin-bottom: 30px;
  font-weight: bold;
}
</style>